/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.config.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Service;

import com.tompai.common.model.SysUser;
import com.tompai.common.util.EnvUtils;
import com.tompai.management.user.service.SysUserService;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义认证成功后处理
 *
 * @author liinux@qq.com
 * @date 2019/10/23
 */
@Slf4j
@Service
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private RequestCache requestCache = new HttpSessionRequestCache();

	@Autowired
	private SysUserService sysUserService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException {
		String currentUserId = EnvUtils.getCurrentUserId();
		SysUser sysUser = sysUserService.getSysUserInfo(currentUserId);
		sysUser.setLastLoginIpAddress(request.getRemoteAddr());
		sysUser.setLastLoginTime(new Date());
		Integer loginCount = sysUser.getLoginCount();
		if (loginCount == null) {
			loginCount = 0;
		}
		sysUser.setLoginCount(loginCount + 1);
		sysUserService.update(sysUser);

		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (null != savedRequest) {
			String targetUrl = savedRequest.getRedirectUrl();
			getRedirectStrategy().sendRedirect(request, response, targetUrl);
			clearAuthenticationAttributes(request);
		} else {
			log.error("Authen failed.");
		}
	}
}
